package com.hejun.redis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RequestMapping("/new")
@Controller
public class NewsController {
    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 更新浏览量
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        Long read = redisTemplate.opsForHash().increment("new_" + id, "read", 1);
        model.addAttribute("read", read);
        Map entries = redisTemplate.opsForHash().entries("new_" + id);
        model.addAttribute("entries", entries);
        return "/new/new"+id;
    }

    @GetMapping
    public String toIndex(){
        return "index";
    }

    /**
     * 点赞
     * @param id
     * @param opType
     * @return
     */
    @RequestMapping("/addZan/{id}/{opType}")
    @ResponseBody
    public Long addZan(@PathVariable Integer id, @PathVariable Integer opType) {
        Long countZan;
        if (opType==1){//点赞
            countZan=redisTemplate.opsForHash().increment("new_"+id,"countZan",1);
        }else {
            countZan=redisTemplate.opsForHash().increment("new_"+id,"countZan",-1);
        }
        return countZan;
    }


}
